package org.xbzheng.sc.core.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.xbzheng.sc.core.util.SecurityUtil;
import org.xbzheng.sc.dao.user.UserDao;
import org.xbzheng.sc.model.Role;
import org.xbzheng.sc.model.User;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by Administrator on 2016/7/13.
 */
@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final User user = userDao.find(username);

        final List<Role> roles = user.getRoles();
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        if(roles != null && !roles.isEmpty()){
            for(Role role: roles){
                authorities.add(new SimpleGrantedAuthority(role.getName()));
            }
        }
        final UserDetailsImpl userDetails = new UserDetailsImpl();
        userDetails.setUsername(user.getUsername());
        userDetails.setPassword(SecurityUtil.aesDecrypt(user.getPassword(), "hun"));
        userDetails.setAuthorities(authorities);
        userDetails.setEnabled(true);
        return userDetails;
    }
}
